<template>
  <div class="box-full flex-col box-border overflow-hidden m-relative dashboard-item">
    <div class="m-absolute b-0 w-full t-0 box-border">
      <a-scrollbar style="height: 100%; overflow-y: auto; overflow-x: hidden">
        <div class="w-full h-10"></div>
        <a-card :bordered="false" class="mb-20 round-8" :loading="topLoading">
          <div class="flex-col flex-a-c w-full">
            <div class="flex flex-a-c">
              <div class="flex-col flex-a-c">
                <span class="text23 font-size-28">可提现余额（元）</span>
                <span class="font-weight-500 font-size-50 mt-18 text23">{{ amount.balance }}</span>
                <span class="text23 font-size-24 mt-18"
                  >*每月25~31日，可提现上月结算{{ userStore.userInfo.rewardChannelStr }}~</span
                >
              </div>
            </div>
            <a-divider />
            <div class="flex flex-wrap w-full flex-j-b">
              <div class="flex-col pl-8 bgF7F7F7 pt-10 pb-10 round-4 st-item">
                <div class="flex flex-a-c">
                  <img class="w-14 h-14" src="@/assets/images/dashboard/t1.png" alt="" />
                  <span class="text463AC9 ml-2 font-size-22">今日预估</span>
                </div>
                <span class="text23 mt-8 font-weight-500 font-size-30"
                  ><span class="font-size-22">￥</span>{{ amount.todayPaidCommission }}</span
                >
              </div>
              <div class="flex-col pl-8 bgF7F7F7 pt-10 pb-10 round-4 st-item">
                <div class="flex flex-a-c">
                  <img class="w-14 h-14" src="@/assets/images/dashboard/t2.png" alt="" />
                  <span class="text463AC9 ml-2 font-size-22">昨日预估</span>
                </div>
                <span class="text23 mt-8 font-weight-500 font-size-30"
                  ><span class="font-size-22">￥</span>{{ amount.yesterdayCommission }}</span
                >
              </div>
              <div class="flex-col pl-8 bgF7F7F7 pt-10 pb-10 round-4 st-item">
                <div class="flex flex-a-c">
                  <img class="w-14 h-14" src="@/assets/images/dashboard/t1.png" alt="" />
                  <span class="text463AC9 ml-2 font-size-22">今日结算</span>
                </div>
                <span class="text23 mt-8 font-weight-500 font-size-30"
                  ><span class="font-size-22">￥</span>{{ amount.todaySettleCommission }}</span
                >
              </div>
              <div class="flex-col pl-8 bgF7F7F7 pt-10 pb-10 round-4 st-item">
                <div class="flex flex-a-c">
                  <img class="w-14 h-14" src="@/assets/images/dashboard/t1.png" alt="" />
                  <span class="text463AC9 ml-2 font-size-22">本月预估</span>
                </div>
                <span class="text23 mt-8 font-weight-500 font-size-30"
                  ><span class="font-size-22">￥</span>{{ amount.stCurrentMonthEstimateCommission }}</span
                >
              </div>
              <div class="flex-col pl-8 bgF7F7F7 pt-10 pb-10 round-4 st-item">
                <div class="flex flex-a-c">
                  <img class="w-14 h-14" src="@/assets/images/dashboard/t2.png" alt="" />
                  <span class="text463AC9 ml-2 font-size-22">上月预估</span>
                </div>
                <span class="text23 mt-8 font-weight-500 font-size-30"
                  ><span class="font-size-22">￥</span>{{ amount.stLastMonthEstimateCommission }}</span
                >
              </div>
              <div class="flex-col pl-8 bgF7F7F7 pt-10 pb-10 round-4 st-item">
                <div class="flex flex-a-c">
                  <img class="w-14 h-14" src="@/assets/images/dashboard/t1.png" alt="" />
                  <span class="text463AC9 ml-2 font-size-22">本月结算</span>
                </div>
                <span class="text23 mt-8 font-weight-500 font-size-30"
                  ><span class="font-size-22">￥</span>{{ amount.stCurrentMonthEarningCommission }}</span
                >
              </div>
              <div class="flex-col pl-8 bgF7F7F7 pt-10 pb-10 round-4 st-item">
                <div class="flex flex-a-c">
                  <img class="w-14 h-14" src="@/assets/images/dashboard/t2.png" alt="" />
                  <span class="text463AC9 ml-2 font-size-22">上月结算</span>
                </div>
                <span class="text23 mt-8 font-weight-500 font-size-30"
                  ><span class="font-size-22">￥</span>{{ amount.stLastMonthEarningCommission }}</span
                >
              </div>
              <div class="flex-col pl-8 bgF7F7F7 pt-10 pb-10 round-4 st-item">
                <div class="flex flex-a-c">
                  <img class="w-14 h-14" src="@/assets/images/dashboard/t3.png" alt="" />
                  <span class="text463AC9 ml-2 font-size-22">今日订单数</span>
                </div>
                <span class="text23 mt-8 font-weight-500 font-size-30"
                  ><span class="font-size-22">￥</span>{{ amount.todayOrderNum }}</span
                >
              </div>
              <div class="flex-col pl-8 bgF7F7F7 pt-10 pb-10 round-4 st-item">
                <div class="flex flex-a-c">
                  <img class="w-14 h-14" src="@/assets/images/dashboard/t3.png" alt="" />
                  <span class="text463AC9 ml-2 font-size-22">今日有效订单数</span>
                </div>
                <span class="text23 mt-8 font-weight-500 font-size-30"
                  ><span class="font-size-22">￥</span>{{ amount.todayPaidOrderNum }}</span
                >
              </div>
              <div class="flex-col pl-8 bgF7F7F7 pt-10 pb-10 round-4 st-item">
                <div class="flex flex-a-c">
                  <img class="w-14 h-14" src="@/assets/images/dashboard/t3.png" alt="" />
                  <span class="text463AC9 ml-2 font-size-22">今日失效订单数</span>
                </div>
                <span class="text23 mt-8 font-weight-500 font-size-30"
                  ><span class="font-size-22">￥</span>{{ amount.todayCancelOrderNum }}</span
                >
              </div>
            </div>
          </div>
        </a-card>
        <div class="flex flex-a-c h-20 mb-14">
          <div class="h-full bg-theme round-2 w-4 mr-10"></div>
          <span class="font-size-30 text333">{{ userStore.userInfo.rewardChannelStr }}看板</span>
          <template v-if="props.allChannel && props.allChannel.length">
            <a-select
              popup-container=".select-box"
              placeholder="选择渠道方筛选"
              v-model="staticParams.channelIds"
              multiple
              allow-clear
              :allow-search="false"
              class="ml-10 mr-20 flex-1"
              :max-tag-count="1"
              @change="channelIdsChange"
            >
              <a-option v-for="item in props.allChannel" :value="item.channelId" :key="item.channelId">{{
                item.name
              }}</a-option>
            </a-select>
          </template>
        </div>
        <a-card :bordered="false" class="round-8">
          <div class="round-8 h-10n bgfff w-full flex flex-a-c">
            <a-select
              :style="{ width: '150px' }"
              v-model="staticParams.platformId"
              :trigger-props="{ autoFitPopupMinWidth: true }"
              @change="dataChange(false)"
            >
              <a-option key="-1" :value="0">全部平台</a-option>
              <a-option v-for="item in platformList" :key="item.platformId" :value="item.platformId">{{
                item.title
              }}</a-option>
            </a-select>
            <div
              v-if="dateTime"
              class="h-32 flex-center round-4 px-10 ml-14"
              style="border: 1px solid var(--color-border-3)"
              @click="openCalendar"
            >
              {{ dateTime[0].format('YY/MM/DD') }} 至 {{ dateTime[1].format('YY/MM/DD') }}
            </div>
            <van-calendar
              :default-date="dateDefault"
              v-model:show="dataShow"
              type="range"
              switch-mode="year-month"
              :show-confirm="false"
              @confirm="onConfirmDate"
            />
          </div>
          <div class="flex flex-a-c mt-10">
            <div class="box-border flex round-4 h-6n border-3 w-fit cursor-pointer mr-10 font-size-22">
              <div
                class="flex-1 h-full flex-center nowrap px-8 box-border round-4 mr-10"
                :class="tabIndex === 1 ? 'bgtheme textfff' : 'border-theme text-theme'"
                @click="changeData(1)"
              >
                今日实时
              </div>
              <div
                class="flex-1 h-full flex-center nowrap px-8 box-border round-4 mr-10"
                :class="tabIndex === 2 ? 'bgtheme textfff' : 'border-theme text-theme'"
                @click="changeData(2)"
              >
                近7天
              </div>
              <div
                class="flex-1 h-full flex-center nowrap px-8 box-border round-4 mr-10"
                :class="tabIndex === 3 ? 'bgtheme textfff' : 'border-theme text-theme'"
                @click="changeData(3)"
              >
                近15天
              </div>
              <div
                class="flex-1 h-full flex-center nowrap px-8 box-border round-4 mr-10"
                :class="tabIndex === 4 ? 'bgtheme textfff' : 'border-theme text-theme'"
                @click="changeData(4)"
              >
                近30天
              </div>
              <div
                class="flex-1 h-full flex-center nowrap px-8 box-border round-4 mr-10"
                :class="tabIndex === 5 ? 'bgtheme textfff' : 'border-theme text-theme'"
                @click="changeData(5)"
              >
                本月
              </div>
              <div
                class="flex-1 h-full flex-center nowrap px-8 box-border round-4"
                :class="tabIndex === 6 ? 'bgtheme textfff' : 'border-theme text-theme'"
                @click="changeData(6)"
              >
                上月
              </div>
            </div>
          </div>
          <a-spin class="w-full" :loading="staticLoading">
            <div class="w-full pb-4">
              <a-checkbox-group class="mt-10 w-full flex flex-wrap flex-j-b" v-model="checkKey">
                <template v-for="item in totalDataO" :key="item.key">
                  <a-checkbox :value="item.value" style="width: calc((100% - 12px) / 3)">
                    <template #checkbox="{ checked }">
                      <a-space
                        align="start"
                        class="custom-checkbox-card"
                        :class="{ 'custom-checkbox-card-checked': checked }"
                      >
                        <div className="custom-checkbox-card-mask">
                          <div className="custom-checkbox-card-mask-dot" />
                        </div>
                        <div class="mt--4">
                          <a-typography-text type="secondary" class="font-size-20 text23">
                            {{ item.label }}<span v-if="item.unit">（{{ item.unit }}）</span>
                          </a-typography-text>
                          <div className="custom-checkbox-card-title">
                            <a-statistic
                              show-group-separator
                              :value="Number(totalDatas[item.key])"
                              :precision="item.precision"
                              :value-from="0"
                              :value-style="{ fontWeight: 'bold' }"
                              animation
                            >
                            </a-statistic>
                          </div>
                        </div>
                      </a-space>
                    </template>
                  </a-checkbox>
                </template>
                <a-checkbox style="width: calc((100% - 12px) / 3); opacity: 0"></a-checkbox>
              </a-checkbox-group>
            </div>
          </a-spin>
          <a-divider />
          <a-spin class="w-full" :loading="staticLoading">
            <Chart ref="ChartRef" :checkKey="checkKey" :dataFormat="dataFormat" />
          </a-spin>
        </a-card>
        <div class="flex flex-a-c h-20 mb-14 mt-14">
          <div class="h-full bg-theme round-2 w-4 mr-10"></div>
          <span class="font-size-30 text333">{{ userStore.userInfo.rewardChannelStr }}明细</span>
        </div>
        <a-card class="mt-m" :bordered="false">
          <a-table
            column-resizable
            size="small"
            stripe
            :sticky-header="-1"
            row-key="date"
            v-model:columns="columns"
            :loading="staticLoading"
            :data="dataList"
            :scroll="{ x: '100%', y: '100%' }"
            :pagination="false"
          >
          </a-table>
        </a-card>
        <div class="w-full h-10"></div>
      </a-scrollbar>
    </div>
  </div>
</template>

<script setup>
import { getOrderStByDate, userCommissionAndBalance } from '@/apis'
import { reAssign } from '@/utils/common'
import { totalDataO } from './data.js'
import dayjs from 'dayjs'
import Chart from './Chart.vue'
import { usePlatform } from '@/hooks'
import { useUserStore } from '@/store'
const userStore = useUserStore()

const props = defineProps(['allChannel'])

const staticLoading = ref(false)
const topLoading = ref(false)
const ChartRef = ref()
const checkKey = ref(['todayPaidCommission'])
const tabIndex = ref()
const dateTime = ref()
const dateDefault = ref()
const dataShow = ref(false)
const staticParams = reactive({
  platformId: 0,
  channelUserIds: [],
  channelIds: []
})
const dataList = ref([])
const dataFormat = ref({
  date: [],
  todayPaidCommission: [],
  todaySettleCommission: [],
  todayOrderNum: [],
  todayPaidOrderNum: [],
  cancelOrderNum: []
})

const totalDatas = reactive({
  paidCommission: 0,
  settleCommission: 0,
  orderNum: 0,
  paidOrderNum: 0,
  cancelOrderNum: 0
})

// 顶部数据
const amount = reactive({
  stCurrentMonthEarningCommission: 0,
  stCurrentMonthEstimateCommission: 0,
  stLastMonthEarningCommission: 0,
  stLastMonthEstimateCommission: 0,
  todayCancelOrderNum: 0,
  todayPaidCommission: 0,
  todayPaidOrderNum: 0,
  todaySettleCommission: 0,
  todayOrderNum: 0,
  yesterdayCommission: 0,
  balance: 0
})
const columns = [
  {
    title: '日期',
    align: 'center',
    width: 120,
    dataIndex: 'date'
  },
  {
    title: `预估${userStore.userInfo.rewardChannelStr}`,
    align: 'center',
    width: 100,
    dataIndex: 'todayPaidCommission',
    render: ({ record }) => {
      return `￥${record.todayPaidCommission}`
    }
  },
  {
    title: `结算${userStore.userInfo.rewardChannelStr}`,
    align: 'center',
    width: 100,
    dataIndex: 'todaySettleCommission',
    render: ({ record }) => {
      return `￥${record.todaySettleCommission}`
    }
  },
  {
    title: '订单数',
    align: 'center',
    width: 90,
    dataIndex: 'todayOrderNum'
  },
  {
    title: '有效订单数',
    align: 'center',
    width: 110,
    dataIndex: 'todayPaidOrderNum'
  },
  {
    title: '失效订单数',
    align: 'center',
    width: 110,
    dataIndex: 'todayCancelOrderNum'
  }
]

// if (props?.allChannel?.length) {
//   staticParams.channelIds = props.allChannel.map((item) => {
//     return item.channelId
//   })
//   staticParams.channelUserIds = props.allChannel.map((item) => {
//     return item.channelUserId
//   })
// }

// 获取平台信息
const { platformList, getPlatformList } = usePlatform()
getPlatformList()

const getTop = async () => {
  try {
    topLoading.value = true
    const res = await userCommissionAndBalance()
    reAssign(amount, res.data)
  } finally {
    topLoading.value = false
  }
}
getTop()
// 获取数据
const onGetStatic = async () => {
  try {
    staticLoading.value = true
    const startAt = dateTime.value[0].format('YYYY-MM-DD HH:mm:ss')
    const endAt = dateTime.value[1].format('YYYY-MM-DD HH:mm:ss')
    const res = await getOrderStByDate({
      startAt,
      endAt,
      platformId: staticParams.platformId || undefined,
      channelIds: staticParams.channelIds,
      channelUserIds: staticParams.channelUserIds
    })
    const mergeData = res.data.merge
    reAssign(totalDatas, mergeData)
    const objSource = {}
    const daysListReverse = JSON.parse(JSON.stringify(res.data.list))
    dataList.value = res.data.list.reverse()
    daysListReverse.forEach((item) => {
      Object.keys(item).forEach((key) => {
        if (!objSource[key]) objSource[key] = []
        if (
          [
            'todayPaidCommission',
            'todaySettleCommission',
            'todayOrderNum',
            'todayPaidOrderNum',
            'todayCancelOrderNum'
          ].includes(key)
        ) {
          item[key] = Number(item[key])
        }
        objSource[key].push(item[key])
      })
    })
    dataFormat.value = objSource
  } finally {
    staticLoading.value = false
  }
}

const changeData = (index) => {
  tabIndex.value = index
  switch (index) {
    case 1:
      dateTime.value = [dayjs().startOf('day'), dayjs().endOf('day')]
      break
    case 2:
      dateTime.value = [dayjs().subtract(7, 'day').startOf('day'), dayjs().subtract(1, 'day').endOf('day')]
      break
    case 3:
      dateTime.value = [dayjs().subtract(15, 'day').startOf('day'), dayjs().subtract(1, 'day').endOf('day')]
      break
    case 4:
      dateTime.value = [dayjs().subtract(30, 'day').startOf('day'), dayjs().subtract(1, 'day').endOf('day')]
      break
    case 5:
      dateTime.value = [dayjs().startOf('month'), dayjs().endOf('day')]
      break
    case 6:
      dateTime.value = [dayjs().subtract(1, 'month').startOf('month'), dayjs().subtract(1, 'month').endOf('month')]
      break
  }
  onGetStatic()
}

const dataChange = (flag) => {
  if (flag) tabIndex.value = null
  onGetStatic()
}

const channelIdsChange = (e) => {
  const channelUserIds = props.allChannel.filter((item) => e.includes(item.channelId)).map((item) => item.channelUserId)
  staticParams.channelIds = e
  staticParams.channelUserIds = channelUserIds
  onGetStatic()
}

// 打开日期选择框
const openCalendar = () => {
  if (dateTime.value) {
    dateDefault.value = [dateTime.value[0].toDate(), dateTime.value[1].toDate()]
  }
  dataShow.value = true
}
// 日期选择回调
const onConfirmDate = (e) => {
  dateTime.value = [dayjs(e[0]).startOf('day'), dayjs(e[1]).endOf('day')]
  dataShow.value = false
  dataChange(true)
}

onMounted(() => {
  setTimeout(() => {
    changeData(2)
  }, 1000)
})
</script>

<style lang="scss" scoped>
.text23 {
  color: #232323;
}
.custom-checkbox-card {
  padding: 9px 0 10px 10px;
  border: 1px solid #62b793;
  border-radius: 4px;
  width: 100%;
  box-sizing: border-box;
  margin-top: 7px;
}

.custom-checkbox-card-mask {
  height: 14px;
  width: 14px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 2px;
  border: 1px solid #62b793;
  box-sizing: border-box;
  margin-top: 3px;
}

.custom-checkbox-card-mask-dot {
  width: 8px;
  height: 8px;
  border-radius: 2px;
}

.custom-checkbox-card-title {
  color: var(--color-text-1);
  font-size: 10px;
  font-weight: bold;
}

.custom-checkbox-card:hover,
.custom-checkbox-card-checked,
.custom-checkbox-card:hover .custom-checkbox-card-mask,
.custom-checkbox-card-checked .custom-checkbox-card-mask {
  border-color: #62b793;
}

.custom-checkbox-card-checked {
  background-color: #f3fffa;
}

.custom-checkbox-card:hover .custom-checkbox-card-title,
.custom-checkbox-card-checked .custom-checkbox-card-title {
  color: #62b793;
}

.custom-checkbox-card-checked .custom-checkbox-card-mask-dot {
  background-color: #62b793;
}

.arco-scrollbar {
  height: 100%;
}

.w-1-4 {
  width: 20%;
}

.select-box {
  :deep(.arco-select-dropdown-list-wrapper) {
    max-height: 300px !important;
  }
}

.text463AC9 {
  color: #463ac9;
}

.text22A164 {
  color: #22a164;
}

.bgF7F7F7 {
  background-color: #f7f7f7;
}

.dashboard-item {
  :deep(.arco-card-body) {
    padding: 20px 12px;
  }
}

.st-item {
  width: calc((100% - 12px) / 3);
  margin-bottom: 14px;
}

:deep(.arco-checkbox) {
  margin-right: 0;
}

:deep(.arco-statistic-value) {
  font-size: 16px;
}

:deep(.arco-table-col-fixed-right .arco-table-cell) {
  padding: 5px 0 !important;
}
</style>
